import { PageContainer } from "@ant-design/pro-components";
import { Button, Card, Col, DatePicker, Form, Input, message, Popconfirm, Row, Select, Space, Spin, Table, Typography } from "antd";
import React, { useEffect, useState, useCallback, useMemo } from "react";
import { deleteUserData, getUserListData } from "./api";
import MyModal from "./components/UpdateForm";
import moment from "moment";
import { ReloadOutlined, SearchOutlined, ClearOutlined } from '@ant-design/icons';
import styles from './index.less';

const { Title, Text } = Typography;

const Setting: React.FC = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [page, setPage] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [total, setTotal] = useState<number>(0);
    const [condition, setCondition] = useState<any>();
    const [isUpdate, setIsUpdate] = useState<boolean>(true);
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
    const [modalData, setModalData] = useState<any>(null);
    const [lastUpdated, setLastUpdated] = useState<Date | null>(null);

    const getUserList = async () => {
        setLoading(true);
        try {
            const params = {
                ...condition,
                page: page,
                pageSize: pageSize,
            }
            const res = await getUserListData(params);
            if (res.code === 200) {
                setData(res.data.userList);
                setTotal(res.data.count);
                setLastUpdated(new Date());
                message.success(res.message);
            } else {
                message.error(res.message);
            }
        } catch (error) {
            console.error('获取用户列表出错:', error);
            message.error('网络错误，请稍后重试');
        } finally {
            setLoading(false);
        }
    }

    useEffect(() => {
        const timer = setTimeout(() => {
            getUserList();
        }, 10);
        return () => {
            clearTimeout(timer);
        };
    }, [page, condition, pageSize, isUpdate]);

    const onFinish = () => {
        const values = {
            username: form.getFieldValue('username') || '',
            account: form.getFieldValue('account') || '',
            permissions: form.getFieldValue('permissions'),
            createdTime: form.getFieldValue('createTime') === null ? '' : form.getFieldValue('createTime') === undefined ? '' : moment(form.getFieldValue('createdTime')).format('YYYY-MM-DD'),
        }
        setCondition(values);
        setPage(1); // 重置到第一页
    };

    const clear = () => {
        form.resetFields();
        setIsUpdate(!isUpdate)
    };

    const handleRefresh = useCallback(() => {
        getUserList();
    }, []);

    const deleteUser = async (id: any) => {
        try {
            const res = await deleteUserData(id);
            if (res.code === 200) {
                message.success(res.message);
                getUserList();
            } else {
                message.error(res.message);
            }
        } catch (error) {
            console.error('删除用户出错:', error);
            message.error('删除失败，请稍后重试');
        }
    }

    const handleSelect = (record: any) => {
        setModalData(record);
        setIsModalOpen(true);
    }

    const pagination = {
        current: page,
        pageSize: pageSize,
        total: total,
        pageSizeOptions: [5, 10, 20, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: () => `共 ${total} 条数据`,
        onChange: (cur: number, p: number) => {
            setPage(cur);
            setPageSize(p);
        },
    };

    const columns: any = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            render: (text: any, record: any, index: number) =>
                `${(pagination.current - 1) * pagination.pageSize + (index + 1)}`,
            width: 80,
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            width: 100,
        },
        {
            title: '账号',
            dataIndex: 'account',
            key: 'account',
            width: 150,
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            width: 150,
        },
        {
            title: '手机号',
            dataIndex: 'phoneNumber',
            key: 'phoneNumber',
            width: 150,
        },
        {
            title: '是否是新用户',
            dataIndex: 'isNew',
            key: 'isNew',
            width: 150,
            render: (text: any) => text === 0 ? '新用户' : '老用户'
        },
        {
            title: '身份',
            dataIndex: 'permissions',
            key: 'permissions',
            width: 150,
            render: (text: any) => text === 0 ? '管理员' : '普通用户'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 150,
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (text: any, record: any) => (
                <Space size="middle" className={styles.actionColumn}>
                    <a className={styles.editLink} onClick={() => handleSelect(record)}>编辑</a>
                    <Popconfirm
                        title="确认删除吗？"
                        onConfirm={() => deleteUser(text.id)}
                        onCancel={() => { }}
                        okText="确定"
                        cancelText="取消"
                    >
                        <a className={styles.deleteLink}>删除</a>
                    </Popconfirm>
                </Space>
            ),
        }
    ];

    // 渲染标题和操作区
    const renderHeader = useMemo(() => (
        <div className={styles.headerWrapper}>
            <Title level={4} className={styles.cardTitle}>
                用户管理
            </Title>
            <div className={styles.headerActions}>
                {lastUpdated && (
                    <Text type="secondary" className={styles.lastUpdated}>
                        最后更新: {lastUpdated.toLocaleTimeString()}
                    </Text>
                )}
                <Button 
                    type="primary" 
                    icon={<ReloadOutlined />} 
                    onClick={handleRefresh}
                    loading={loading}
                    className={styles.refreshButton}
                >
                    刷新数据
                </Button>
            </div>
        </div>
    ), [lastUpdated, loading, handleRefresh]);

    return (
        <PageContainer className={styles.container}>
            <Card className={styles.formCard} bordered={false}>
                <Form form={form} onFinish={onFinish} layout="vertical" className={styles.searchForm}>
                    <Row gutter={16}>
                        <Col span={5}>
                            <Form.Item
                                label="用户名"
                                name="username"
                            >
                                <Input placeholder="请输入用户名" />
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Form.Item
                                label="账号"
                                name="account"
                            >
                                <Input placeholder="请输入账号" />
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Form.Item
                                label="身份"
                                name="permissions"
                            >
                                <Select placeholder="请选择身份">
                                    <Select.Option key={0} value={0}>
                                        管理员
                                    </Select.Option>
                                    <Select.Option key={1} value={1}>
                                        普通用户
                                    </Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item
                                label="创建时间"
                                name="createdTime"
                            >
                                <DatePicker
                                    style={{ width: '100%' }}   
                                    picker="date"
                                    format="YYYY-MM-DD"
                                    placeholder="请选择日期" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row justify="end">
                        <Space className={styles.formButtons}>
                            <Button 
                                htmlType="submit" 
                                type="primary" 
                                icon={<SearchOutlined />}
                            >
                                查询
                            </Button>
                            <Button 
                                htmlType="button" 
                                onClick={clear} 
                                icon={<ClearOutlined />}
                            >
                                重置
                            </Button>
                        </Space>
                    </Row>
                </Form>
            </Card>
            
            <Card 
                className={styles.contentCard}
                title={renderHeader}
                bordered={false}
            >
                <Spin spinning={loading} tip="加载中..." className={styles.spinner}>
                    <div className={styles.tableContainer}>
                        <Table
                            className={styles.dataTable}
                            columns={columns}
                            dataSource={data}
                            bordered={false}
                            pagination={pagination}
                            size="middle"
                            rowKey="id"
                            scroll={{ x: 1000 }}
                        />
                    </div>
                </Spin>
            </Card>

            <MyModal
                isOpen={isModalOpen}
                setIsModalOpen={setIsModalOpen}
                setIsUpdate={setIsUpdate}
                isUpdate={isUpdate}
                modalData={modalData}
            />
        </PageContainer>
    );
}

export default Setting;

